package com.example.libary.controller;

import com.example.libary.common.Result;
import com.example.libary.entity.BookCategory;
import com.example.libary.service.BookCategoryService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 图书分类控制器
 */
@Tag(name = "图书分类管理", description = "图书分类管理相关接口")
@RestController
@RequestMapping("/categories")
@RequiredArgsConstructor
public class BookCategoryController {

    private final BookCategoryService bookCategoryService;

    /**
     * 查询分类列表
     */
    @Operation(summary = "查询分类列表", description = "查询所有分类")
    @GetMapping
    public Result<List<BookCategory>> getAllCategories() {
        List<BookCategory> list = bookCategoryService.list((String) null);
        return Result.success(list);
    }

    /**
     * 查询分类列表
     */
    @Operation(summary = "查询分类列表", description = "查询所有分类")
    @GetMapping("/list")
    public Result<List<BookCategory>> list(
            @Parameter(description = "分类名称") @RequestParam(required = false) String name) {
        List<BookCategory> list = bookCategoryService.list(name);
        return Result.success(list);
    }

    /**
     * 查询分类树
     */
    @Operation(summary = "查询分类树", description = "查询分类树形结构")
    @GetMapping("/tree")
    public Result<List<BookCategory>> tree() {
        List<BookCategory> tree = bookCategoryService.tree();
        return Result.success(tree);
    }

    /**
     * 根据父ID查询子分类
     */
    @Operation(summary = "查询子分类", description = "根据父ID查询子分类")
    @GetMapping("/parent/{parentId}")
    public Result<List<BookCategory>> listByParentId(
            @Parameter(description = "父分类ID") @PathVariable Long parentId) {
        List<BookCategory> list = bookCategoryService.listByParentId(parentId);
        return Result.success(list);
    }

    /**
     * 获取分类详情
     */
    @Operation(summary = "获取分类详情", description = "根据ID获取分类详情")
    @GetMapping("/{id}")
    public Result<BookCategory> getCategory(@Parameter(description = "分类ID") @PathVariable Long id) {
        BookCategory category = bookCategoryService.getById(id);
        return Result.success(category);
    }

    /**
     * 添加分类
     */
    @Operation(summary = "添加分类", description = "管理员权限")
    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping
    public Result<Void> addCategory(
            @Parameter(description = "分类信息") @RequestBody @Valid BookCategory category) {
        // 检查分类名称是否存在
        if (bookCategoryService.checkNameExists(category.getName(), null)) {
            return Result.error("分类名称已存在");
        }
        boolean success = bookCategoryService.save(category);
        return success ? Result.success() : Result.error("添加失败");
    }

    /**
     * 更新分类
     */
    @Operation(summary = "更新分类", description = "管理员权限")
    @PreAuthorize("hasRole('ADMIN')")
    @PutMapping("/{id}")
    public Result<Void> updateCategory(
            @Parameter(description = "分类ID") @PathVariable Long id,
            @Parameter(description = "分类信息") @RequestBody @Valid BookCategory category) {
        category.setId(id);
        // 检查分类名称是否存在
        if (bookCategoryService.checkNameExists(category.getName(), id)) {
            return Result.error("分类名称已存在");
        }
        boolean success = bookCategoryService.updateById(category);
        return success ? Result.success() : Result.error("更新失败");
    }

    /**
     * 删除分类
     */
    @Operation(summary = "删除分类", description = "管理员权限")
    @PreAuthorize("hasRole('ADMIN')")
    @DeleteMapping("/{id}")
    public Result<Void> deleteCategory(@Parameter(description = "分类ID") @PathVariable Long id) {
        // 检查是否有子分类
        List<BookCategory> children = bookCategoryService.listByParentId(id);
        if (!children.isEmpty()) {
            return Result.error("该分类下有子分类，不能删除");
        }
        boolean success = bookCategoryService.removeById(id);
        return success ? Result.success() : Result.error("删除失败");
    }
} 